<?php

namespace Iwesen\Sem\Track\Advertisers;

class Zhihu
{
    //列举常用的转化类型
    const API_SUBMIT        = 'api_submit';//表单提交';
    const API_ASK           = 'api_ask';//有效咨询';
    const API_CALL          = 'api_call';//电话拨打';
    const API_BUY           = 'api_buy';// 商品购买 实际花费';
    const API_VIEW          = 'api_view';//页面访问';
    const API_GET_CUST      = 'api_get_cust';//有效获客';
    const API_PAY           = 'api_pay';// 付费 实际花费';

    public function callback($param)
    {
        if (!isset($param['link']) || !$link = $param['link']) {
            throw new \Exception('link  is required!');
        }
        if (!isset($param['event_type']) || !$event_type = $param['event_type']) {
            throw new \Exception('event_type is not a exist !');
        }
        try {
            $time = time();
            $url = str_replace('__EVENTTYPE__', $event_type, $link);
            $url = str_replace('__TIMESTAMP__', $time, $url);
            if (isset($param['event_value']) && $eventValue = $param['event_value']) {
                $url = str_replace('__EVENTVALUE__', $eventValue, $url);
            }

            $result = (new Request())->_request($url);
            $data = json_decode($result, true);
            if (in_array($data['httpCode'], [200, 204])) {
                return 'success';
            }

            return 'fail';
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
}
